package com.boxin.ims.modules.wechat.busi;

import java.util.Date;


import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.boxin.ims.modules.wechat.entity.LangType;
import com.boxin.ims.modules.wechat.entity.MemberScore;
import com.boxin.ims.modules.wechat.entity.RecommendConfig;
import com.boxin.ims.modules.wechat.entity.WeChat;
import com.boxin.ims.modules.wechat.entity.WechatMember;
import com.boxin.ims.modules.wechat.entity.tmessage.BusinessMessageTemplate;
import com.boxin.ims.modules.wechat.entity.tmessage.UserMessageTemplate;
import com.boxin.ims.modules.wechat.service.MemberScoreService;
import com.boxin.ims.modules.wechat.service.RecommendConfigService;
import com.boxin.ims.modules.wechat.service.WeChatService;
import com.boxin.ims.modules.wechat.service.tmessage.UserMessageTemplateService;
import com.boxin.ims.modules.wechat.tmessage.TemplateMessage;
import com.boxin.ims.modules.wechat.tmessage.TemplateMessageFactory;
import com.boxin.ims.modules.wechat.utils.ScoreUtils;
import com.boxin.ims.modules.wechat.utils.TemplateMessageUtils;
import com.boxin.ims.modules.wechat.utils.TokenUtils;
import com.boxin.ims.modules.wechat.utils.WechatInterfaceUtils;
import com.thinkgem.jeesite.common.utils.CacheUtils;
import com.thinkgem.jeesite.common.utils.DateUtils;
//import com.thinkgem.jeesite.common.utils.JedisUtils;
/**
 * @author hjt
 * @date 2016-3-16
 * @function <p> 三级推广</p>
 */
@Service
@Scope("prototype")
public class ExpandProcessor extends BusinessProcessor{

	@Autowired
	private RecommendConfigService recommendConfigService;
	
	@Autowired
	private WeChatService weChatService;
	
	@Autowired
	private UserMessageTemplateService userMessageTemplateService;
	
	@Autowired
	private MemberScoreService memberScoreService;
	
	public RecommendConfig getRecommendConfig(String uid){
		String key = "recommend_config_"+uid;
		Object object = CacheUtils.get(key);
		if(object!=null){
			return (RecommendConfig) object;
		}else{
//			object =	JedisUtils.getObject(key);
			/*if(object!=null){
				return (RecommendConfig) object;
			}else{*/
				RecommendConfig config = recommendConfigService.getByUserId(Long.parseLong(uid));
//				JedisUtils.setObject(key, config, 0);
				CacheUtils.put(key, config);
				return config;
//			}
		}
	}
	
	@Override
	public ProcessMessage process() {
		
		RecommendConfig recommendConfig = getRecommendConfig(user.getId().toString());
		if(recommendConfig==null) return null;
		
		if(RecommendConfig.NO.equals(recommendConfig.getIsOpen()))return null;
		
		Date date = new Date();
		if(recommendConfig.getStartTime().getTime()>date.getTime() || date.getTime()>recommendConfig.getEndTime().getTime())return null;
		
		WechatMember tempMember = wechatMemberService.getByWechatMemberId(user, openId); 					//关注者
		
		
//		System.out.println(varMap.get("flag")+"--------->>>>>>>>>>>SSSSSSSSSS>>>>>>>>>>");
		
		if(!(boolean) varMap.get("flag")){//判断是否是第一次关注
//			System.out.println("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSs");
			
			if(DateUtils.getMinute(new Date(),tempMember.getCreateTime())>1){
				//向关注者发送客服
			    try {
			    	String content = recommendConfig.getRepetitionMessage().replace("memberName", tempMember.getName());
			    	WechatInterfaceUtils.sendTextMessageToMember(tempMember.getUser().getId(), tempMember, content);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
			return null;
		}
		
		// 修改 会员，上级会员，上上级会员积分
		String sceneId = (String)varMap.get("sceneId");
		
		WechatMember parentMember = wechatMemberService.get(Long.parseLong(sceneId));					//推荐者
		WechatMember grandMember = null;
		if(parentMember!=null && StringUtils.isNotBlank(parentMember.getParentCode())){
			grandMember = wechatMemberService.getByRecommandCode(parentMember.getParentCode());		//上上级
		}
		
		
		String dosc = "";
		if(parentMember!=null && parentMember.getId()!=null && parentMember.getId()>0){
			
			//给关注者的父推荐码设置推荐码
			tempMember.setParentCode(parentMember.getRecommendCode());
			tempMember.setRecommendScore(tempMember.getRecommendScore()==null?recommendConfig.getOneselfScore():tempMember.getRecommendScore()+recommendConfig.getOneselfScore());
			wechatMemberService.save(tempMember);
			
			String content = "您成功邀请了您的朋友"+tempMember.getName()+"，奖励您"+recommendConfig.getParentScore()+"积分"; 
			//加积分
			if("0".equals(recommendConfig.getType())){
				ScoreUtils.addRecommendScore(parentMember,recommendConfig.getParentScore(),"积分兑奖品："+content,MemberScore.TYPE_RECOMMEND_TEMP);
				
			}else if("1".equals(recommendConfig.getType())){
				MemberScore memberScore  = new MemberScore();
				memberScore.setWechatMember(parentMember);
				memberScore.setType(MemberScore.TYPE_RECOMMEND_TEMP);
				memberScore.setUser(parentMember.getUser());
				memberScore.setScore(recommendConfig.getParentScore());			//操作的分数，有可能是负数 
				memberScore.setRemarks("积分排名送奖品："+content);
				memberScoreService.save(memberScore);
			}
			
			dosc = "您已成功为"+parentMember.getName()+"增加"+recommendConfig.getParentScore()+"积分。您增加了5积分。您也可以生成自己的海报，让好友帮您免费得到保洁服务！";
			//发模板消息
			sendTemplateMessage(parentMember, recommendConfig.getParentScore(), content);
		}
		
		
		
		if(grandMember!=null && grandMember.getId() != null && grandMember.getId()>0){
			//判断会员积分大于0
			if(grandMember.getScore()>0){
				
				String content = "你的朋友"+ parentMember.getName()+"也邀请了一个朋友"+tempMember.getName()+"，奖励您"+recommendConfig.getGrandScore()+"积分。";
				//加积分
				if("0".equals(recommendConfig.getType())){
					//ScoreUtils.addScore(grandMember,recommendConfig.getGrandScore(),"积分兑奖品："+content,MemberScore.TYPE_RECOMMEND_TEMP);
					
					ScoreUtils.addRecommendScore(grandMember,recommendConfig.getGrandScore(),"积分兑奖品："+content,MemberScore.TYPE_RECOMMEND_TEMP);
					
				}else if("1".equals(recommendConfig.getType())){
					MemberScore memberScore  = new MemberScore();
					memberScore.setWechatMember(grandMember);
					memberScore.setType(MemberScore.TYPE_RECOMMEND_TEMP);
					memberScore.setUser(grandMember.getUser());
					memberScore.setScore(recommendConfig.getGrandScore());			//操作的分数，有可能是负数 
					memberScore.setRemarks("积分排名送奖品："+content);
					memberScoreService.save(memberScore);
				}
				
				dosc = dosc + "为"+grandMember.getName()+"增加"+recommendConfig.getGrandScore()+"积分。";
				//发模板消息
				sendTemplateMessage(grandMember, recommendConfig.getGrandScore(), content);
				
			}else{
				//积分小于0	通过微信平台，判断是否关注平台
				try {
					WeChat weChat =  weChatService.getWeChatByUserId(grandMember.getUser().getId());
					String token = TokenUtils.getAPIToken(weChat);
					
					WechatMember member = WechatInterfaceUtils.getUserMessage(token,grandMember.getWechatId(),	LangType.zh_CN);
					
//					if(WechatMember.SUBSCRIBE.equals(member.getSubscribe())){
						String content = "你的朋友"+ parentMember.getName()+"也邀请了一个朋友"+tempMember.getName()+"，奖励您"+recommendConfig.getGrandScore()+"积分。";
						
						//加积分
						if("0".equals(recommendConfig.getType())){
							//ScoreUtils.addScore(grandMember,recommendConfig.getGrandScore(),"积分兑奖品："+content,MemberScore.TYPE_RECOMMEND_TEMP);
							
							ScoreUtils.addRecommendScore(grandMember,recommendConfig.getGrandScore(),"积分兑奖品："+content,MemberScore.TYPE_RECOMMEND_TEMP);
							
						}else if("1".equals(recommendConfig.getType())){
							MemberScore memberScore  = new MemberScore();
							memberScore.setWechatMember(grandMember);
							memberScore.setType(MemberScore.TYPE_RECOMMEND_TEMP);
							memberScore.setUser(grandMember.getUser());
							memberScore.setScore(recommendConfig.getGrandScore());			//操作的分数，有可能是负数 
							memberScore.setRemarks("积分排名送奖品："+content);
							memberScoreService.save(memberScore);
						}
						
						dosc = dosc + "为"+grandMember.getName()+"增加"+recommendConfig.getGrandScore()+"积分。";
						//发模板消息
						sendTemplateMessage(grandMember, recommendConfig.getGrandScore(), content);
//					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	
		//给会员发送消息：告知他帮助了谁得到了多少积分
		
		
   	try {
		WechatInterfaceUtils.sendTextMessageToMember1(tempMember.getUser().getId(), tempMember, dosc+"\n\n"+recommendConfig.getParentMessage());
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
		
		
		
		
		
		/*if(StringUtils.isNotBlank(dosc)){
			writeToUser(dosc+"\n\n"+recommendConfig.getParentMessage());
		}*/
		
		
		
		
		return null;
	}
	
	
	public void sendTemplateMessage(WechatMember wechatMember, Integer score, String reason){

		UserMessageTemplate messageTemplate= userMessageTemplateService.getUserMessageTemplateByBid(wechatMember.getUser().getId(), BusinessMessageTemplate.MEMBER_SCORE_CHANGE);
		if(messageTemplate!=null){
			//获得token
 			WeChat weChat =  weChatService.getWeChatByUserId(wechatMember.getUser().getId());
 			String token = TokenUtils.getAPIToken(weChat);
			
			String keyword1="";		//会员名称 
			if(StringUtils.isNotBlank(wechatMember.getName())){
				keyword1 = wechatMember.getName();
			}else if(StringUtils.isNotBlank(wechatMember.getNickname())){
				keyword1 = wechatMember.getNickname();
			}else{
				keyword1 = "匿名";
			}
			String keyword2=wechatMember.getRecommendCode();		//消费积分
			
			TemplateMessage templateMessage = TemplateMessageFactory.createWechatMember
					(wechatMember.getWechatId(),messageTemplate.getTemplateId(),"",keyword1,keyword2,reason,"","");
			TemplateMessageUtils.sendTemplateMessage(token, templateMessage);
		}
	}
	

	@Override
	public boolean isNeedBeMember() {
		return false;
	}
	
}
